#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
配置管理器 - 从INI文件读取配置
"""

import os
import sys
import configparser
from pathlib import Path
from typing import Dict, Any, Optional

class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_file: str = "config.ini"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self._load_config()
    
    def _load_config(self):
        """加载配置文件"""
        # 获取配置文件路径
        config_path = self._get_config_path()
        
        # 如果配置文件不存在，创建默认配置
        if not config_path.exists():
            print(f"⚠️ 配置文件不存在: {config_path}")
            self._create_default_config()
            config_path = self._get_config_path()
        
        # 读取配置文件
        try:
            self.config.read(config_path, encoding='utf-8')
            print(f"✅ 配置文件加载成功: {config_path.absolute()}")
        except Exception as e:
            print(f"❌ 配置文件加载失败: {e}")
            self._create_default_config()
    
    def _get_config_path(self) -> Path:
        """获取配置文件路径，支持PyInstaller打包"""
        # 检查是否在PyInstaller打包环境中运行
        if getattr(sys, 'frozen', False):
            # PyInstaller打包后的环境
            application_path = Path(sys.executable).parent
            config_path = application_path / self.config_file
            print(f"🔍 PyInstaller环境，配置文件路径: {config_path}")
        else:
            # 开发环境
            config_path = Path(self.config_file)
            print(f"🔍 开发环境，配置文件路径: {config_path}")
        
        return config_path
    
    def _create_default_config(self):
        """创建默认配置文件"""
        print("📝 创建默认配置文件...")
        
        # 设置默认配置
        self.config['SERVER'] = {
            'host': '0.0.0.0',
            'port': '8000',
            'debug': 'False'
        }
        
        self.config['MONITOR'] = {
            'base_path': r'D:\exam',
            'auto_start': 'True',
            'scan_interval': '5'
        }
        
        self.config['DATABASE'] = {
            'db_path': 'orders.db',
            'backup_enabled': 'True',
            'backup_interval': '24'
        }
        
        self.config['WEBSOCKET'] = {
            'max_connections': '100',
            'ping_interval': '30',
            'ping_timeout': '10'
        }
        
        # 保存配置文件
        config_path = self._get_config_path()
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                self.config.write(f)
            print(f"✅ 默认配置文件创建成功: {config_path.absolute()}")
        except Exception as e:
            print(f"❌ 默认配置文件创建失败: {e}")
    
    def get(self, section: str, key: str, fallback: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            section: 配置节
            key: 配置键
            fallback: 默认值
            
        Returns:
            配置值
        """
        try:
            return self.config.get(section, key, fallback=fallback)
        except (configparser.NoSectionError, configparser.NoOptionError):
            return fallback
    
    def getint(self, section: str, key: str, fallback: int = 0) -> int:
        """获取整数配置值"""
        try:
            return self.config.getint(section, key, fallback=fallback)
        except (configparser.NoSectionError, configparser.NoOptionError, ValueError):
            return fallback
    
    def getfloat(self, section: str, key: str, fallback: float = 0.0) -> float:
        """获取浮点数配置值"""
        try:
            return self.config.getfloat(section, key, fallback=fallback)
        except (configparser.NoSectionError, configparser.NoOptionError, ValueError):
            return fallback
    
    def getboolean(self, section: str, key: str, fallback: bool = False) -> bool:
        """获取布尔配置值"""
        try:
            return self.config.getboolean(section, key, fallback=fallback)
        except (configparser.NoSectionError, configparser.NoOptionError, ValueError):
            return fallback
    
    def set(self, section: str, key: str, value: Any):
        """
        设置配置值
        
        Args:
            section: 配置节
            key: 配置键
            value: 配置值
        """
        if not self.config.has_section(section):
            self.config.add_section(section)
        
        self.config.set(section, key, str(value))
    
    def save(self):
        """保存配置文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                self.config.write(f)
            print(f"✅ 配置文件保存成功: {Path(self.config_file).absolute()}")
        except Exception as e:
            print(f"❌ 配置文件保存失败: {e}")
    
    def get_server_config(self) -> Dict[str, Any]:
        """获取服务器配置"""
        return {
            'host': self.get('SERVER', 'host', 'localhost'),
            'port': self.getint('SERVER', 'port', 8000),
            'debug': self.getboolean('SERVER', 'debug', False)
        }
    
    def get_monitor_config(self) -> Dict[str, Any]:
        """获取监控配置"""
        return {
            'base_path': self.get('MONITOR', 'base_path', r'D:\exam'),
            'auto_start': self.getboolean('MONITOR', 'auto_start', True),
            'scan_interval': self.getint('MONITOR', 'scan_interval', 5)
        }
    
    def get_database_config(self) -> Dict[str, Any]:
        """获取数据库配置"""
        return {
            'db_path': self.get('DATABASE', 'db_path', 'orders.db'),
            'backup_enabled': self.getboolean('DATABASE', 'backup_enabled', True),
            'backup_interval': self.getint('DATABASE', 'backup_interval', 24)
        }
    
    def get_websocket_config(self) -> Dict[str, Any]:
        """获取WebSocket配置"""
        return {
            'max_connections': self.getint('WEBSOCKET', 'max_connections', 100),
            'ping_interval': self.getint('WEBSOCKET', 'ping_interval', 30),
            'ping_timeout': self.getint('WEBSOCKET', 'ping_timeout', 10)
        }
    
    def reload(self):
        """重新加载配置文件"""
        self._load_config()
        print("🔄 配置文件重新加载完成")
    
    def get_all_config(self) -> Dict[str, Dict[str, Any]]:
        """获取所有配置"""
        return {
            'server': self.get_server_config(),
            'monitor': self.get_monitor_config(),
            'database': self.get_database_config(),
            'websocket': self.get_websocket_config()
        }


# 全局配置管理器实例
config_manager = ConfigManager()


def get_config() -> ConfigManager:
    """获取全局配置管理器实例"""
    return config_manager
